﻿using System;
using System.Security.Principal;
using nRoute.Components;
using nRoute.Components.Messaging;
using nRoute.SiteMaps;

namespace nRoute.Samples.SiteMapClient.Components
{
	public class UserSiteMapProvider : ISiteMapProvider
	{
		private readonly RelayObservable<SiteMap> _siteMapRelay;
		private readonly ChannelObserver<IPrincipal> _principalObserver;

		public UserSiteMapProvider()
		{
			_siteMapRelay = new RelayObservable<SiteMap>();
			_principalObserver = new ChannelObserver<IPrincipal>(OnLogin);
			_principalObserver.Subscribe(true);
		}

#region ISiteMapProvider

		public IObservable<SiteMap> ResolveSiteMap()
		{
			return _siteMapRelay;
		}

#endregion

#region Helpers

		private void OnLogin(IPrincipal principal)
		{
			// get user siteMap
			ResolveUserSiteMap(principal, (sm) =>
			{
				_siteMapRelay.OnNext(sm);
				_siteMapRelay.OnCompleted();
			});

			// dispose the channel since we don't need it anymore
			_principalObserver.Dispose();
		}

		private void ResolveUserSiteMap(IPrincipal principal, Action<SiteMap> onResolveSiteMap)
		{
			// with user specifics in hand get the sitemap and return using onResolveSiteMap
			throw new NotImplementedException();
		}

#endregion

	}
}